﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using WeBlog.Interfaces;
using WeBlog.Repositories;
using WeBlog.Widgets;

namespace WeBlog
{
    public class WidgetManager
    {
        private static CompositionContainer _container;
        private static AggregateCatalog _catalog;
        private readonly DirectoryInfo _rootDirectory;
        private const string WidgetPattern = "*Widget.dll";

        [ImportMany(typeof(IWidget), AllowRecomposition = true)]
        public IEnumerable<IWidget> RegisteredWidgets
        {
            get;
            set;
        }

        public IWidget FindBySlug( string slug )
        {
            return RegisteredWidgets.SingleOrDefault(x => x.Name.Equals(slug,StringComparison.CurrentCultureIgnoreCase));
        }        

        public WidgetManager(DirectoryInfo rootDirectory)
        {
            _rootDirectory = rootDirectory;
            DiscoverWidgets();
        }

        private void DiscoverWidgets()
        {
            //search the widget directory and also the current assembly for Widgets
            _catalog = new AggregateCatalog(
                new DirectoryCatalog(_rootDirectory.FullName, WidgetPattern),
                new AssemblyCatalog(Assembly.GetExecutingAssembly()));
            _container = new CompositionContainer(_catalog);
            _container.ComposeParts(this);
        }
    }
}
